<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
                        <el-form-item label="输入数据库" prop="inputDataId">
                          <el-select style="width: 100%;" filterable clearable v-model="queryParams.inputDataId"
                                     placeholder="请选择输入数据库">
                            <el-option
                              v-for="item in jobDatasource"
                              :key="item.id"
                              :label="`${item.name}【${item.username}】`"
                              :value="item.id"
                            ></el-option>
                          </el-select>
                        </el-form-item>
                        <el-form-item label="输出数据库" prop="outputDataId">
                          <el-select style="width: 100%;" filterable clearable v-model="queryParams.outputDataId"
                                     placeholder="请选择输出数据库">
                            <el-option
                              v-for="item in jobDatasource"
                              :key="item.id"
                              :label="`${item.name}【${item.username}】`"
                              :value="item.id"
                            ></el-option>
                          </el-select>
                        </el-form-item>
                        <el-form-item label="输出表名" prop="outputTable">
                            <el-input
                                    v-model="queryParams.outputTable"
                                    placeholder="请输入输出表名"
                                    clearable
                                    @keyup.enter.native="handleQuery"
                            />
                        </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="el-icon-plus"
                        size="mini"
                        @click="handleAdd"
                        v-hasPermi="['kettle:details:add']"
                >新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="success"
                        plain
                        icon="el-icon-edit"
                        size="mini"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['kettle:details:edit']"
                >修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="danger"
                        plain
                        icon="el-icon-delete"
                        size="mini"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['kettle:details:remove']"
                >删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="warning"
                        plain
                        icon="el-icon-download"
                        size="mini"
                        @click="handleExport"
                        v-hasPermi="['kettle:details:export']"
                >导出</el-button>
            </el-col>
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  plain
                  icon="el-icon-edit-outline"
                  size="mini"
                  @click="handleUpdateOrderNum"
                  v-hasPermi="['kettle:details:orderNum']"
                >保存顺序</el-button>
              </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-check"
              size="mini"
              :disabled="single"
              @click="handleJobTaskDetail"
              v-hasPermi="['kettle:details:execute']"
            >执行</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-close"
              size="mini"
              @click="handleClose"
            >关闭</el-button>
          </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

      <el-table border="border" max-height="550px" v-loading="loading" :data="detailsList"
                @selection-change="handleSelectionChange" @row-click="rowClick"
                @sort-change="handleSortChange" :row-style="tableRowStyle" ref="details">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="操作"
                         v-hasPermi="['kettle:details:query']"
                         align="center" width="100" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleUpdate(scope.row,false)"
              v-hasPermi="['reportworld:details:query']"
            >详情</el-button>
          </template>
        </el-table-column>
        <el-table-column label="执行类型" align="center" prop="ftype" width="150" :show-overflow-tooltip="true" sortable="custom"
                         :sort-orders="['descending', 'ascending']">
          <template slot-scope="scope">{{ scope.row.ftype === 1 ? '输入输出' : scope.row.ftype === 2 ? '执行SQL':
            scope.row.ftype === 3 ? "读取DBF": "读取EXECL"}}
          </template>
        </el-table-column>
        <el-table-column label="输入数据库" align="center" prop="inputDataId" :formatter="datasourceNameInput" width="150" :show-overflow-tooltip="true" sortable="custom"
                         :sort-orders="['descending', 'ascending']">
        </el-table-column>
        <el-table-column label="输出数据库" align="center" prop="outputDataId" :formatter="datasourceNameOutput" width="150" :show-overflow-tooltip="true"
                         sortable="custom" :sort-orders="['descending', 'ascending']"/>
        <el-table-column label="执行SQL" align="center" prop="inputSql" width="150" :show-overflow-tooltip="true" sortable="custom"
                         :sort-orders="['descending', 'ascending']"/>
        <el-table-column label="输出表名" align="center" prop="outputTable" width="150" :show-overflow-tooltip="true" sortable="custom"
                         :sort-orders="['descending', 'ascending']"/>
        <el-table-column label="顺序" align="center" prop="orderNum" :show-overflow-tooltip="true" sortable="custom"
                         :sort-orders="['descending', 'ascending']"/>
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_common_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="添加时间" align="center" prop="createTime" width="180" sortable="custom"
                         :sort-orders="['descending', 'ascending']">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="添加人" align="center" width="150" prop="createBy" :show-overflow-tooltip="true"
                         sortable="custom" :sort-orders="['descending', 'ascending']"/>
        <el-table-column label="编辑时间" align="center" prop="updateTime" width="180" sortable="custom"
                         :sort-orders="['descending', 'ascending']">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="编辑人" align="center" width="150" prop="updateBy" :show-overflow-tooltip="true"
                         sortable="custom" :sort-orders="['descending', 'ascending']"/>
        <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" sortable="custom"
                         :sort-orders="['descending', 'ascending']"/>
      </el-table>
        <pagination
                v-show="total>0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
        />

        <!-- 添加或修改作业任务明细信息对话框 -->
      <el-dialog v-if="open" :title="title" :close-on-click-modal ="false" :visible.sync="open" width="1200px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="执行类型" prop="ftype">
                <el-select  v-model="form.ftype" placeholder="请选择执行类型" clearable>
                  <el-option
                    v-for="dict in ftypes"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="输入数据库" prop="inputDataId">
                <el-select style="width: 100%;" filterable clearable v-model="form.inputDataId"
                           placeholder="请选择输入数据库">
                  <el-option
                    v-for="item in jobDatasource"
                    :key="item.id"
                    :label="`${item.name}【${item.username}】`"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="输出数据库" prop="outputDataId"
                            v-if="(form.ftype === 1 ||  form.ftype === 3 ||  form.ftype === 4) ? true:false"
                            :rules="(form.ftype === 1 ||  form.ftype === 3 ||  form.ftype === 4) ? [{ required: true, message: '输出数据库不能为空'}]:rules.target"
              >
              <el-select style="width: 100%;" filterable clearable v-model="form.outputDataId"
                         placeholder="请选择输出数据库">
                <el-option
                  v-for="item in jobDatasource"
                  :key="item.id"
                  :label="`${item.name}【${item.username}】`"
                  :value="item.id"
                ></el-option>
              </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="输出表名" prop="outputTable"
                            v-if="(form.ftype === 1 ||  form.ftype === 3 ||  form.ftype === 4) ? true:false"
                            :rules="(form.ftype === 1 ||  form.ftype === 3 ||  form.ftype === 4) ? [{ required: true, message: '输出表名不能为空'}]:rules.target"
              >
                <el-input clearable v-model="form.outputTable" placeholder="请输入输出表名"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="执行SQL" prop="inputSql">
                <monaco-editor ref="monacoEditor"  style="border:1px solid #000;" :opts="opts"></monaco-editor>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="顺序" prop="orderNum">
                <el-input-number style="width: 100%" v-model="form.orderNum" controls-position="right" :min="1"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio
                    v-for="dict in dict.type.sys_common_status"
                    :key="dict.value"
                    :label="parseInt(dict.value)"
                  >{{dict.label}}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input maxlength="500" v-model="form.remark" type="textarea" placeholder="请输入内容"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" v-if="isUpdate" :loading="butloading" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>


      <el-dialog title="任务执行参数" :close-on-click-modal ="false" :visible.sync="openParam" width="800px" append-to-body>
        <div style="height:400px;overflow:auto;">
          <el-form ref="formParam" :model="formParam" :rules="rulesParam" label-width="100px">
            <el-row>
              <el-col :span="12" v-for="(item, index) in headList" :key="index">
                <el-form-item v-if="item.datatype"  :label="item.chineseName" :prop="item.keyName">
                  <el-input clearable  v-if="item.datatype == 1 || item.datatype == 2" v-model="formParam[item.keyName]"></el-input>
                  <el-date-picker clearable  v-if="item.datatype == 4"
                                  v-model="formParam[item.keyName]"
                                  type="date"
                                  value-format="yyyy-MM-dd">
                  </el-date-picker>
                  <el-date-picker clearable  v-if="item.datatype == 5"
                                  v-model="formParam[item.keyName]"
                                  type="datetime"
                                  value-format="yyyy-MM-dd HH:mm:ss">
                  </el-date-picker>
                  <el-select clearable  v-if="item.datatype == 3" v-model="formParam[item.keyName]">
                    <el-option
                      v-for="dict in item.options"
                      :key="dict.keyId"
                      :label="dict.keyName"
                      :value="dict.keyId"
                    />
                  </el-select>
                  <el-radio-group  v-if="item.datatype == 'radio'" v-model="formParam[item.keyName]">
                    <el-radio
                      v-for="dict in item.options"
                      :key="dict.value"
                      :label="dict.value"
                    >{{dict.label}}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="executeJobTaskDetail">确 定</el-button>
            <el-button @click="openParam = false">取 消</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>
    import { listDetails, getDetails, delDetails, addDetails, updateDetails ,init,handleUpdateOrderNum,executeJobTaskDetail} from "@/api/kettle/details";
    import { listParam} from "@/api/kettle/task";
    import { getTableRowStyle } from "@/utils/yss";
    import monacoEditor from '@/components/SqlEditor';
    import Sortable from "sortablejs";
    export default {
       name: "TaskDetails",
      components:{
        monacoEditor
      },
      dicts: ['sys_common_status'],
        data() {
          const equalToDataSql = (rule, value, callback) => {
            if (this.$refs.monacoEditor.getVal()) {
              callback()
            } else {
              callback(new Error("SQL语句不能为空"));
            }
          };
            return {
              butloading:false,
              isUpdate: false,
              ftypes: [
                {
                  value: 1,
                  label: "输入输出"
                },
                {
                  value: 2,
                  label: "执行SQL"
                } ,
                {
                  value: 3,
                  label: "读取DBF"
                } ,
                {
                  value: 4,
                  label: "读取EXECL"
                }
              ],
                // 遮罩层
                loading: true,
                // 选中数组
                ids: [],
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                // 作业任务明细信息表格数据
                detailsList: [],
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                //数据来源
                jobDatasource:null,
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 50,
                    id: null,
                    taskId: null,
                    ftype: null,
                    inputDataId: null,
                    outputDataId: null,
                    inputSql: null,
                    outputTable: null,
                    orderNum: null,
                    status: null,
                    createTime: null,
                    createBy: null,
                    updateTime: null,
                    updateBy: null,
                    remark: null
             },
              opts: { //编辑器
                value: '',
                readOnly: false, // 是否可编辑
                language: 'sql', // 语言类型
                theme: 'vs', // 编辑器主题
                lineNumbers: "on", // 行号 取值
              },
              queryParams2: {
                pageNum: 1,
                pageSize: 1000
              },
              // 参数选择弹出
              openParam:false,
              headList:[],
              formParam:{},
              rulesParam:{},
            // 表单参数
            form: {},
            // 表单校验
            rules: {
              inputDataId: [
                { required: true, message: "输入数据库部能为空", trigger: "blur" }
              ],
              inputSql: [
                {
                  required: true,
                  validator: equalToDataSql,
                  message: "SQL语句不能为空",
                  trigger: ["blur"]
                }
              ]
            }
        };
        },
        created() {
          const id = this.$route.params && this.$route.params.id;
          this.queryParams.taskId = id;
          this.init();
          this.getList();
        },
        methods: {
          handleJobTaskDetail(){
            listParam(this.queryParams2).then(response => {
              this.openParam = true;
            this.headList = [];
            response.rows.map(x=>{
              if(x.required == 1){
              this.headList.push(x);
            }
          })
            this.headList = Object.assign([],this.headList);
            this.rulesParam = {};
            this.headList.map(x=>{
              this.rulesParam[x.keyName] = [];
            if(x.required == 1){
              this.rulesParam[x.keyName].push({required: true,message: '请输入'+x.chineseName,trigger: 'blur'})
              this.formParam[x.keyName]=x.defaultValue;
            }
          });
          });
          },
          executeJobTaskDetail(){
            this.$refs["formParam"].validate((valid) => {
              if (valid) {
                this.formParam["ids"] = this.ids;
                this.formParam["headList"] = this.headList;
                this.openParam = false;
                executeJobTaskDetail(JSON.stringify(this.formParam)).then(response => {

              });
              }
            });
          },
          /** 返回按钮操作 */
          handleClose() {
            const obj = { path: "/kettle/task" };
            this.$tab.closeOpenPage(obj);
          },
          datasourceNameInput(row,colum){
             for(let i in this.jobDatasource){
                if(row.inputDataId == this.jobDatasource[i].id){
                   return this.jobDatasource[i].name;
                }
             }
            return row.inputDataId;
           },
          datasourceNameOutput(row,colum){
              for(let i in this.jobDatasource){
                if(row.outputDataId == this.jobDatasource[i].id){
                  return this.jobDatasource[i].name;
                }
              }
               return row.outputDataId;
            },
            /** 查询作业任务明细信息列表 */
            getList() {
                this.loading = true;
                listDetails(this.queryParams).then(response => {
                this.detailsList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
            },
            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            // 表单重置
            reset() {
                this.form = {
                        id: null,
                        taskId: null,
                        ftype: null,
                        inputDataId: null,
                        outputDataId: null,
                        inputSql: null,
                        outputTable: null,
                        orderNum: null,
                        status: null,
                        createTime: null,
                        createBy: null,
                        updateTime: null,
                        updateBy: null,
                        remark: null
            };
                this.resetForm("form");
            },
            init(){
              init().then(response => {
                this.jobDatasource=response.jobDatasource;
            });
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.resetForm("queryForm");
                this.handleQuery();
            },
            // 多选框选中数据
            handleSelectionChange(selection) {
                this.ids = selection.map(item => item.id)
                this.single = selection.length!==1
                this.multiple = !selection.length
            },
            // 保存排序
            handleUpdateOrderNum(){
              this.loading = true;
              let arrTaskDetail = [];
              for (let index in this.detailsList) {
                const taskDetail = Object.assign({});
                taskDetail.id= this.detailsList[index].id;
                taskDetail.orderNum =parseInt(index) + 1;
                arrTaskDetail.push(taskDetail);
              }
              handleUpdateOrderNum(arrTaskDetail).then(response => {
                this.loading = false;
                this.$modal.msgSuccess("保存顺序成功");
            });
              this.getList();
            },
            /** 排序触发事件 */
            handleSortChange(column, prop, order) {
                this.queryParams.orderByColumn = column.prop;
                this.queryParams.isAsc = column.order;
                this.getList();
            },
            /** 新增按钮操作 */
            handleAdd() {
                this.reset();
                this.open = true;
                this.form.taskId =this.queryParams.taskId;
                this.opts.value= '';
                this.title = "添加作业任务明细信息";
                this.open = true;
                this.isUpdate =true;
                this.form.status = parseInt(this.dict.type.sys_common_status[0].value);
            },
            /** 修改按钮操作 */
            handleUpdate(row,isUpdate) {
                this.reset();
                const id = row.id || this.ids
                getDetails(id).then(response => {
                this.form = response.data;
                this.opts.value= '';
                this.opts.value= response.data.inputSql;
                this.open = true;
                this.title = "修改作业任务明细信息";
                this.isUpdate =true;
                if(isUpdate == false){
                  this.title = "作业任务明细信息详情";
                  this.isUpdate =false;
                }
            });
            },
            /** 提交按钮 */
            submitForm() {
                this.$refs["form"].validate(valid => {
                    if (valid) {
                      this.butloading=true;
                        this.form.inputSql = this.$refs.monacoEditor.getVal();
                        if (this.form.id != null) {
                            updateDetails(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        }).finally(() => {this.butloading=false});
                        } else {
                            addDetails(this.form).then(response => {
                                this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        }).finally(() => {this.butloading=false});
                        }
                    }
                });
            },
            /** 删除按钮操作 */
            handleDelete(row) {
                const ids = row.id || this.ids;
                this.$modal.confirm('是否确认删除数据项？').then(function() {
                    return delDetails(ids);
                }).then(() => {
                    this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {});
            },
    /** 导出按钮操作 */
    handleExport() {
        this.download('kettle/details/export', {
                ...this.queryParams
    }, `details_${new Date().getTime()}.xlsx`)
    },
    tableRowStyle({ row, rowIndex}){
        return getTableRowStyle(row,rowIndex,this.ids);
    },
    /** 单击选中行数据 */
    rowClick(row) {
       this.$refs.details.toggleRowSelection(row);
    }
    },
      mounted() {
        const el =  document.querySelector('.el-table__body-wrapper tbody')
        const sortable = Sortable.create(el, {
          onEnd: evt => {
          const targetRow = this.detailsList.splice(evt.oldIndex, 1)[0];
        this.detailsList.splice(evt.newIndex, 0, targetRow);
        for (let index in this.detailsList) {
          this.detailsList[index].sort = parseInt(index) + 1;
        }
      }
      });
      }
    };
</script>
